<?php
// 应用公共文件

use app\admin\model\DeviceModel;
use app\admin\model\ImeiModel;
use Firebase\JWT\JWT;
use think\facade\Config;
use think\facade\Cache;

// 成功输出
function success($data = [], $message = 'success')
{
    return json(['code' => 1, 'message' => $message, 'status' => 10001, 'data' => $data]);
}
// 失败输出
function fail($data = [], $message = 'fail')
{
    return json(['code' => -1, 'message' => $message, 'status' => 10002, 'data' => $data]);
}
// 错误输出
function error($message = 'error', $data = [])
{
    return json(['code' => -1, 'message' => $message, 'status' => 10003, 'data' => $data]);
}

function getToken($uidKey, $uidVal)
{
    $key = 'locateMiNiToken';
    $payload = [
        "iat"   => time(),                  //签发时间
        "nbf"   => time(),                  //如果当前时间在nbf里的时间之前，则Token不被接受（提示token过期）
        "exp"   => time() + 60 * 60 * 24,   //过期时间
        $uidKey => $uidVal,
    ];
    $token = JWT::encode($payload, $key, "HS256");
    // Cache::store('redis')->set("fm" . $data['uidVal'] . 'token', $callback['token'], 60 * 60 * 24); //token储存30天=2592000秒
    return $token;
}

// 密码加密
function encryptPwd($salt, $pwd)
{
    return base64_encode(json_encode($salt . $pwd));
}

// 手机号加密
function encryptMobile($salt, $mobile)
{
    return base64_encode(json_encode('mobile' . $salt . $mobile));
}

/* @Notes 生成随机字符串
 * @param type string num|case|mix
 * @param int string 字符串长度
 */
function getRandStr(string $type, int $length = 11): String
{
    if ($type === 'num') {
        $str = '0123456789';
    } else if ($type === 'mix_letter') {
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    } else if ($type === 'mix_letter_num') {
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    } else if ($type === 'big_letter_num') {
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    }
    $len = strlen($str) - 1;
    $randstr = '';
    for ($i = 0; $i < $length; $i++) {
        $num = mt_rand(0, $len);
        $randstr .= $str[$num];
    }
    return $randstr;
}

// 根据经纬度获取地址
function getAddressInfo($lng, $lat)
{
    $url = 'https://restapi.amap.com/v3/geocode/regeo?location=' . $lng . ',' . $lat . '&key=4eb2f588230103dc7ceefd9de2445cae';
    $result = file_get_contents($url);
    return json_decode($result, true);
}

// 更新imei编码表
function upImei($id, $key, $status)
{
    $deviceModel = new DeviceModel();
    $imeiModel = new ImeiModel();
    $imei = $deviceModel->where('id', $id)->value('device_imei');
    $imeiModel->getUpdate(['imei' => $imei], [$key => $status, 'utime' => time()]);
    return true;
}
// http request
function http($url, $params, $method = 'GET', $header = array(), $multi = false)
{
    $opts = array(
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER     => $header
    );
    /* set parameters */
    switch (strtoupper($method)) {
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式！');
    }
    /* initialize curl */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data  = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) throw new Exception('请求发生错误：' . $error);
    return  $data;
}
